package part21;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wcj
 * @Date 2021/6/9 16:18
 * @Version 1.0
 */
public class Part2117 {

    /**
     * atomic下的原子类可以保证增加等操作的原子性，最主要是底层实际上使用的是os的系统原语也就是原子指令
     *
     * @param args
     */
    public static void main(String[] args) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Aborting");
                System.exit(0);
            }
        }, 5000);

        ExecutorService exec = Executors.newCachedThreadPool();
        AtomicIntegerTest atomicIntegerTest = new AtomicIntegerTest();
        exec.execute(atomicIntegerTest);
        while (true) {
            int val = atomicIntegerTest.getValue();
            if (val % 2 != 0) {
                System.out.println(val);
                System.exit(0);
            }
        }
    }
}

class AtomicIntegerTest implements Runnable {

    private AtomicInteger i = new AtomicInteger();

    public int getValue() {
        return i.get();
    }

    public void evenIncrement() {
        i.addAndGet(2);
    }

    @Override
    public void run() {
        while (true) {
            evenIncrement();
        }
    }

}
